<template>
	<view class="order-view">
		<!-- <u-radio-group v-model="radiovalue1" placement="row" v-if="goodsDetail.standby3 && !isSale"> -->
		<u-radio-group v-model="radiovalue1" placement="row" v-if="!isSale">
			<u-radio labelSize="16" activeColor="#000" :customStyle="{marginBottom: '8px'}" v-for="(item, index) in radiolist1" :key="index"
				:label="item.name" :name="item.name" @change="radioChange">
			</u-radio>
		</u-radio-group>

		<view class="order-addr" v-if="!this.buyer && selectOrder == 1">
			<OrderAddr isClick="true" @selectAddr="selectAddr" v-if="defAddr">
				<text slot="addr">{{defAddr.detailsAddress}} {{defAddr.streetAddress}} {{defAddr.city}}</text>
				<view slot="nameMobile">{{defAddr.firstName}} {{defAddr.lastName}} {{defAddr.phoneNumber}}</view>
			</OrderAddr>
			<OrderAddr isClick="true" @selectAddr="selectAddr" isNot="true" v-else>
				<view slot="not">{{$t("confirmOrder.not")}}</view>
			</OrderAddr>
		</view>

		<view class="order-addr" v-if="!this.buyer && selectOrder == 2">
			<OrderAddr isClick="true" @selectAddr="selectAddr" v-if="defAddr">
				<text slot="addr">{{defAddr.detailsAddress}} {{defAddr.streetAddress}} {{defAddr.city}}</text>
				<view slot="nameMobile">{{defAddr.firstName}} {{defAddr.lastName}} {{defAddr.phoneNumber}}</view>
			</OrderAddr>
			<OrderAddr isClick="true" @selectAddr="selectAddr" isNot="true" v-else>
				<view slot="not"></view>
			</OrderAddr>
		</view>

		<view class="goods-msg">
			<image :src="goodsDetail.morebagPublishPictures[0].picture"
				mode="aspectFit"></image>
			<view class="goods-msg-right">
				<view class="name">
					{{$t("goodsReleased.language") == "zh"?goodsDetail.commodity:goodsDetail.commodityEn}}
				</view>
				<view class="color">
					{{$t("confirmGoodsOrder.sku")}}：{{goodsDetail.measurement}}
				</view>
				<view class="price-count">
					<view class="price">
						$ {{String((bid?bid:goodsDetail.money)).replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}
					</view>
					<!-- <u-number-box inputWidth="20" buttonSize="25" bgColor="#fff" disabledInput v-model="value" @change="valChange"></u-number-box> -->
				</view>
			</view>
		</view>

		<!-- <view class="hint" v-if="!defAddr">
			<image src="../../static/icon/image_20.png" mode=""></image>
			<view class="sup">
				{{$t("confirmOrder.sup")}}
			</view>
		</view> -->

		<view class="explain">
			<view class="item">
				<view class="desc">
					{{$t("confirmGoodsOrder.fre")}}
				</view>
				<view class="price">
<!--					$ {{freightMoney}}-->
					$ {{ flog ? -freightMoney : freightMoney }}
				</view>
			</view>

			<view class="item">
				<view class="desc">
					{{$t("confirmGoodsOrder.charge")}}
				</view>
				<view class="price">
<!--					$ {{brokerage}}-->
					$ {{ flog ? -brokerage : brokerage }}
				</view>
			</view>

			<view class="item">
				<view class="desc">
					{{$t("confirmGoodsOrder.tax")}}<text>(10%)</text>
				</view>
				<view class="price">
<!--					$ {{tax}}-->
					$ {{ flog ? -tax : tax }}
				</view>
			</view>

			<view class="item">
				<view class="desc">
					{{$t("confirmGoodsOrder.discount")}}
				</view>
				<view class="price">
<!--					$ {{discount}}-->
          $ {{ flog ? -discount : discount }}
				</view>
			</view>

			<view class="acc-pay">
				<view class="acc">
					{{$t("confirmGoodsOrder.pay")}}：
				</view>

				<view class="pay">
<!--					$ {{showTotalPrice}}-->
          $ {{((flog ? showTotalPrice - 2*freightMoney - 2 * brokerage - 2 * tax - 2 * discount : showTotalPrice) || 0).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}
				</view>
			</view>
		</view>

		<!-- <view class="timeout">
			{{$t("confirmGoodsOrder.downTime")}}：23:59
		</view> -->

		<view class="btn" v-if="!isSale">
			<view class="toggleCart" @tap="offlinePay">{{$t("confirmGoodsOrder.offline")}}</view>
			<view class="toggleBuy" @tap="createOrderPost">{{$t("confirmGoodsOrder.line")}}</view>
		</view>

		<view class="btn" v-else>
			<!-- <view class="toggleCart" @tap="offlinePay">{{$t("confirmGoodsOrder.offline")}}</view> -->
			<view class="toggleBuy2" @tap="createOrderPost">{{$t("confirmGoodsOrder.title")}}</view>
		</view>

		<u-loading-page :loading="loading" loadingMode="spinner" bg-color="rgba(32, 31, 31, 0.7)" :loadingText="$t('confirmGoodsOrder.hint1')" iconSize ="32" fontSize="18" color="#e5e5e5" loadingColor="#e5e5e5" :vertical="true"></u-loading-page>
	</view>
</template>

<script>
	import {
		createOrder,
		getFreightMoney,
		getAboutUs,
		showMoney,
		getUserName,
		getUserCid,
		getShop,getShop1
	} from "@/common/api.js"

	export default {
		data() {
			return {
        //false立即购买 true商品发布列表进入
        flog:false,
				outUserName: "",
				addUserName: "",
				value: "",
				goodsDetail: "",
				defAddr: null,
				bid: null,
				tax: null,
				loading: false,
				totalPrice: null,
				isSale: false,
				saleId: null,
				buyer: null,
				freightMoney: null,
				brokerage: null,
				showTotalPrice: null,
				isClick: true,
				selectOrder: 1,
				discount: null,
				// 基本案列数据
				radiolist1: [{
						name: this.$t("confirmGoodsOrder.select2"),
						id: 1
					},
					{
						name: this.$t("confirmGoodsOrder.select1"),
						id: 2
					},
				],
				// u-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
				radiovalue1: this.$t("confirmGoodsOrder.select2"),
			}
		},
    mounted() {
      getShop1(this.saleId).then(res => {
        const rows = res.rows || [];
        if (rows.length > 0) {
          this.defAddr=rows[0]
          // uni.setStorageSync("companyAddr", rows[0]);
        }
      });
    },
		methods: {
			async offlinePay() {
				if (!this.defAddr) {
					uni.showToast({
						icon: 'none',
						title: this.$t("confirmGoodsOrder.hint"),
						duration: 1200
					})
					return
				}
				// const tax = this.bid?this.bid:this.goodsDetail.money * 0.1;
				if (!this.totalPrice) {
					return
				}
				if (!this.isClick) {
					return
				}
				this.isClick = false;
				console.log("线下支付");
				this.loading = true;
				const res = await createOrder({
					shopId: this.goodsDetail.id,
					freightId: this.goodsDetail.freightId || 1,
					taxId: 1,
					commodityName: this.goodsDetail.commodity,
					commodityNameEn: this.goodsDetail.commodityEn,
					orderMoney: this.bid ? this.bid : this.goodsDetail.money,
					tax: this.tax,
					freightMoney: this.freightMoney || 0,
					overMoney: this.totalPrice,
					// paymentProof: 1,
					payState: 6,
					orderState: this.selectOrder == 1?0:60,
					// createOrderTime: time,
					orderStatus: this.selectOrder == 1?0:60,
					addressId: this.defAddr.id,
					outUserId: this.goodsDetail.customerId,
					addUserId: this.saleId,
					serviceMoney: this.brokerage,
					outUserName: this.outUserName,
					addUserName: this.addUserName,
					vmoney: this.discount
				});
				console.log(res);
				if (res.code === 200) {
					console.log(res);
					this.loading = false;
					uni.redirectTo({
						url: `/pages/myOrder/myOrder`
					})
				} else {
					this.loading = false;
					uni.showToast({
						icon: 'none',
						title: res.msg,
						duration: 1200
					})
					return
				}
			},
			async radioChange(n) {
				const res = this.radiolist1.filter(item => item.name == n)
				this.selectOrder = res[0].id;

				if(!uni.getStorageSync("companyAddr")) {
					const {rows} = await getShop();
					uni.setStorageSync("companyAddr", rows[0]);
				}

				if(this.selectOrder == 2) {
					const companyAddr = uni.getStorageSync("companyAddr");
					this.defAddr = companyAddr;
					uni.removeStorageSync("companyAddr");
				} else {
					const selAddr = uni.getStorageSync("selectAddr");
					this.defAddr = selAddr;
					uni.removeStorageSync("selectAddr");
					this.initAddr();
				}
				console.log(this.selectOrder);
			},
			// 选择地址
			selectAddr() {
				if(this.selectOrder == 1) {
					uni.navigateTo({
						url: "/pages/addrManage/addrManage?order=1"
					})
				} else {
					uni.navigateTo({
						url: "/pages/addrManage/addrManage?order=1&store=1"
					})
				}
			},
			valChange(e) {
				console.log('当前值为: ' + e.value)
			},
			getNowTime() {
				const yy = new Date().getFullYear()
				const MM = (new Date().getMonth() + 1) < 10 ? '0' + (new Date().getMonth() + 1) : (new Date().getMonth() +
					1)
				const dd = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate()
				const HH = new Date().getHours() < 10 ? '0' + new Date().getHours() : new Date().getHours()
				const mm = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
				const ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
				return yy + '-' + MM + '-' + dd + ' ' + HH + ':' + mm + ':' + ss
			},
			createOrderPost() {
				if (!this.defAddr && !this.isSale) {
					uni.showToast({
						icon: 'none',
						title: this.$t("confirmGoodsOrder.hint"),
						duration: 1200
					})
					return
				}
				// const tax = this.bid?this.bid:this.goodsDetail.money * 0.1;
				if (!this.totalPrice) {
					return
				}
				if (!this.isClick) {
					return
				}
				this.isClick = false;
				const time = this.getNowTime();
				// orderState 买家
				// orderStates 卖家
				this.loading = true;
				if (this.isSale) {
					this.saleCreateOrder(time);
				} else {
					this.buyerCreateOrder(time);
				}
			},
			async saleCreateOrder(time) {
				const res = await createOrder({
					shopId: this.goodsDetail.id,
					freightId: this.goodsDetail.freightId || 1,
					taxId: 1,
					commodityName: this.goodsDetail.commodity,
					commodityNameEn: this.goodsDetail.commodityEn,
					orderMoney: this.bid ? this.bid : this.goodsDetail.money,
					tax: this.tax,
					freightMoney: this.freightMoney || 0,
					overMoney: this.totalPrice,
					// paymentProof: 1,
					// payState: 1,
					orderState: 0,
					// createOrderTime: time,
					orderStatus: 0,
					addressId: this.defAddr.id,
					outUserId: this.saleId,
					addUserId: this.buyer.userId,
					bidId: this.buyer.id,
					serviceMoney: this.brokerage,
					outUserName: this.outUserName,
					addUserName: this.addUserName,
					vmoney: this.discount
				});
				console.log(res);

				if (res.code === 200) {
					this.loading = true;

					// #ifdef APP
					const resCid = await getUserCid(this.buyer.userId);
					console.log(resCid);
					uniCloud.callFunction({
						name:"push",
						data:{
						  cids:resCid.data.cid,
						  title: this.$t('appNotice.title'),
						  content: this.$t('appNotice.paymentContent1') + this.goodsDetail.commodity + this.$t('appNotice.paymentContent2')
						},
						success: (res) => {
							console.log(res);
						},
						fail: (f) => {
							console.log(f);
						}
					  })
					// #endif

					uni.redirectTo({
						url: `/pages/goodsPublish/goodsPublish`
					})
				} else {
					this.loading = false;
					uni.showToast({
						icon: 'none',
						title: res.msg,
						duration: 1200
					})
					return
				}
			},
			async buyerCreateOrder(time) {
				const res = await createOrder({
					shopId: this.goodsDetail.id,
					freightId: this.goodsDetail.freightId || 1,
					taxId: 1,
					commodityName: this.goodsDetail.commodity,
					commodityNameEn: this.goodsDetail.commodityEn,
					orderMoney: this.bid ? this.bid : this.goodsDetail.money,
					tax: this.tax,
					freightMoney: this.freightMoney || 0,
					overMoney: this.totalPrice,
					// paymentProof: 1,
					// payState: 1,
					orderState: this.selectOrder == 2?60:0,
					// createOrderTime: time,
					orderStatus: this.selectOrder == 2?60:0,
					addressId: this.defAddr.id,
					outUserId: this.goodsDetail.customerId,
					addUserId: this.saleId,
					serviceMoney: this.brokerage,
					outUserName: this.outUserName,
					addUserName: this.addUserName,
					vmoney: this.discount
				});
				console.log(res);
				if (res.code === 200) {
					console.log(res);
					this.loading = true;
					uni.redirectTo({
						url: `/pages/selectPay/selectPay?item=${encodeURIComponent(JSON.stringify(this.goodsDetail))}&price=${this.totalPrice}&orderId=${res.data}&selectOrder=${this.selectOrder}`
					})
				} else {
					this.loading = false;
					uni.showToast({
						icon: 'none',
						title: res.msg,
						duration: 1200
					})
					return
				}
			},
			async initUserName() {
				console.log("请求用户名");
				if(this.isSale) {
					const res = await getUserName(this.buyer.userId);
					console.log(res);
					this.outUserName = uni.getStorageSync("userInfo").userName;
					this.addUserName = res.data.userName;
				} else {
					const res = await getUserName(this.goodsDetail.customerId);
					console.log(res);
					this.addUserName = uni.getStorageSync("userInfo").userName;
					this.outUserName = res.data.userName;
				}
			},
			initAddr() {
				if (this.defAddr) {
					return
				}
				if (this.selectOrder == 2) {
					return
				}
				this.defAddr = uni.getStorageSync("defAddr");
				console.log(this.defAddr);
			},
			userSelectAddr() {
				const selAddr = uni.getStorageSync("selectAddr");
				const companyAddr = uni.getStorageSync("companyAddr");
				if (selAddr) {
					this.defAddr = selAddr;
					uni.removeStorageSync("selectAddr");
				} else {
					this.defAddr = companyAddr;
					uni.removeStorageSync("companyAddr");
				}
			},
			async mathMoney() {
				if (this.buyer) {
					this.goodsDetail["outMoneyId"] = this.buyer.id;
				}
				const res = await showMoney(this.goodsDetail);
				console.log(res);
				if (res.code === 200) {
					this.tax = res.data.tax;
					this.freightMoney = res.data.freightMoney;
					this.brokerage = res.data.procedureMoney;
					this.totalPrice = res.data.sum;
					this.discount = res.data.multiply;

					if (String(res.data.sum).split(".")[1]) {
						// this.showTotalPrice = (String(res.data.sum).split(".")[0].replace(/(\d)(?=(?:\d{3})+$)/g,
						this.showTotalPrice = res.data.sum;
					} else {
						// this.showTotalPrice = String(res.data.sum).replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
						this.showTotalPrice = res.data.sum;
					}
				}
			}
		},
		onShow() {
			this.userSelectAddr();
			this.initAddr();
			this.initUserName();
			this.mathMoney();
		},
		onLoad(option) {
			if (option.item) {
				this.goodsDetail = JSON.parse(decodeURIComponent(option.item));
			}
      if (option.flog)
        this.flog=true;

			if (option.buyer) {
				this.buyer = JSON.parse(decodeURIComponent(option.buyer));
				console.log(this.buyer);
			}
			// console.log(decodeURIComponent(option));
			if (option.bid) {
				this.isSale = true;
			}
      console.log(111,this.flog)
			this.bid = option.bid || this.goodsDetail.money;
			this.saleId = uni.getStorageSync("userId");

			// this.initFreightMoney();
			// this.initServiceChange();
			// console.log(option.brokerage, option.freightMoney);
			// this.brokerage = option.brokerage;
			// this.freightMoney = option.freightMoney;
			// let tempTax = String(this.bid ? this.bid : this.goodsDetail.money);
			// let lastNum = tempTax[tempTax.length - 1];
			// tempTax = tempTax.substring(0, tempTax.length - 1);
			// tempTax += "." + lastNum;
			// this.tax = Number(tempTax);
			// let temp = String(Number((this.bid ? this.bid : this.goodsDetail.money)) + this.tax).split(".");
			// temp = this.add(temp.join("."), option.brokerage);
			// temp = this.add(temp, option.freightMoney);
			// console.log(temp);
			// temp = String(temp).split(".");
			// this.totalPrice = temp[0].replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') + "." + (temp[1] ? temp[1] : "00");
			// console.log(this.saleId, this.buyer.userId);
			// if(option.addrItem) {
			// 	this.defAddr = JSON.parse(decodeURIComponent(option.addrItem?option.addrItem:{}));
			// } else {
			// 	this.initAddr();
			// }
		},
		onReady() {
			if(this.isSale) {
				uni.setNavigationBarTitle({
					title: this.$t("confirmGoodsOrder.title2")
				});
			} else {
				uni.setNavigationBarTitle({
					title: this.$t("confirmGoodsOrder.title")
				});
			}
		}
	}
</script>

<style>
	page {
		background-color: #FBFBFB;
	}
</style>
<style lang="scss" scoped>
	.u-fade-enter-active {
		position: relative;
		z-index: 2;
	}

	.u-radio {
		margin-left: 30rpx;
	}

	.u-radio-group {
		margin-top: 30rpx;
	}

	.order-view {
		padding: 0 24rpx;
		position: relative;
	}

	.order-addr {
		margin: 20rpx 0;
		height: 152rpx;
		border-radius: 20rpx;
		background-color: #fff;
		box-shadow: 0rpx 2rpx 16rpx 0rpx #00000019;
	}

	.goods-msg {
		margin-top: 20rpx;
		border-radius: 20rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 2rpx 16rpx 0rpx #00000019;
		padding: 30rpx 20rpx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		position: relative;
		z-index: 1;

		image {
			width: 240rpx;
			height: 225rpx;
			border-radius: 20rpx;
		}

		.goods-msg-right {
			height: 225rpx;
			display: flex;
			flex-direction: column;
			align-items: flex-start;
			justify-content: space-between;
			margin-left: 20rpx;
			flex: 1;

			.name {
				width: 364rpx;
				line-height: 40rpx;
				color: #000000;
				font-family: PingFang SC;
				font-weight: bold;
				font-size: 24rpx;
			}

			.color {
				color: #858585;
				font-family: PingFang SC;
				font-weight: bold;
				font-size: 24rpx;
				margin-bottom: 20rpx;
			}

			.price-count {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.price {
					color: #FAAD67;
					font-family: PingFang SC;
					font-weight: bold;
					font-size: 36rpx;
				}
			}
		}
	}

	.hint {
		position: absolute;
		top: 400rpx;
		margin-left: 12rpx;
		width: 684rpx;
		height: 80rpx;
		border-radius: 20rpx;
		background: #F8F8F8;
		box-shadow: 0rpx 4rpx 8rpx 0rpx #0000003F;
		display: flex;
		align-items: center;
		justify-content: center;

		image {
			width: 40rpx;
			height: 40rpx;
		}

		.sup {
			color: #FF0000;
			font-family: PingFang SC;
			font-weight: regular;
			font-size: 28rpx;
			margin-left: 16rpx;
		}
	}

	.explain {
		padding: 0 40rpx;
		border-radius: 20rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 2rpx 16rpx 0rpx #00000019;
		padding-top: 50rpx;
		margin-top: -50rpx;
		padding-bottom: 32rpx;
		position: relative;
		z-index: 0;
		margin-bottom: 230rpx;

		.item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 30rpx 0;
			border-bottom: 2rpx dashed #858585;

			.desc {
				color: #000000;
				font-family: PingFang SC;
				font-weight: bold;
				font-size: 30rpx;

				text {
					font-size: 20rpx;
					color: #858585;
				}
			}

			.price {
				color: #FAAD67;
				font-family: PingFang SC;
				font-weight: bold;
				font-size: 30rpx;
			}
		}

		.item:last-child {
			border: none;
		}

		.acc-pay {
			margin-top: 62rpx;
			display: flex;
			align-items: center;
			justify-content: flex-end;

			.acc {
				color: #000000;
				font-family: PingFang SC;
				font-weight: bold;
				font-size: 30rpx;
			}

			.pay {
				color: #FF0000;
				font-family: PingFang SC;
				font-weight: bold;
				font-size: 50rpx;
			}
		}
	}

	.btn {
		width: 100%;
		display: flex;
		position: fixed;
		height: 112rpx;
		bottom: 0;
		left: 0;
		font-family: PingFang SC;
		font-weight: bold;
		font-size: 32rpx;
		border-radius: 0rpx;
		text-align: center;
		line-height: 112rpx;

		.toggleCart {
			background: #F1F1F1;
			width: 50%;
			color: #858585;
		}

		.toggleBuy {
			width: 50%;
			background: #000000;
			color: #FFFFFF;

		}

		.toggleBuy2 {
			width: 100%;
			background: #000000;
			color: #FFFFFF;

		}
	}

	.timeout {
		position: fixed;
		left: 0;
		width: 100%;
		bottom: 112rpx;
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
		background: #FFFFFF;
		box-shadow: 0rpx -2rpx 16rpx 0rpx #0000000C;
		color: #858585;
		font-family: PingFang SC;
		font-weight: bold;
		font-size: 36rpx;
	}
</style>
